home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-gdata / atom / http.py < prev    next >
Encoding:
Python Source  |  2008-12-03  |  10.0 KB  |  287 lines

  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2008 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. #      http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16.  
  17.  
  18. """HttpClients in this module use httplib to make HTTP requests.
  19.  
  20. This module make HTTP requests based on httplib, but there are environments
  21. in which an httplib based approach will not work (if running in Google App
  22. Engine for example). In those cases, higher level classes (like AtomService
  23. and GDataService) can swap out the HttpClient to transparently use a 
  24. different mechanism for making HTTP requests.
  25.  
  26.   HttpClient: Contains a request method which performs an HTTP call to the 
  27.       server.
  28.       
  29.   ProxiedHttpClient: Contains a request method which connects to a proxy using
  30.       settings stored in operating system environment variables then 
  31.       performs an HTTP call to the endpoint server.
  32. """
  33.  
  34.  
  35. __author__ = 'api.jscudder (Jeff Scudder)'
  36.  
  37.  
  38. import types
  39. import os
  40. import httplib
  41. import atom.url
  42. import atom.http_interface
  43. import socket
  44. import base64
  45.  
  46.  
  47. class ProxyError(atom.http_interface.Error):
  48.   pass
  49.  
  50.  
  51. DEFAULT_CONTENT_TYPE = 'application/atom+xml'
  52.  
  53.  
  54. class HttpClient(atom.http_interface.GenericHttpClient):
  55.   def __init__(self, headers=None):
  56.     self.debug = False
  57.     self.headers = headers or {}
  58.  
  59.   def request(self, operation, url, data=None, headers=None):
  60.     """Performs an HTTP call to the server, supports GET, POST, PUT, and 
  61.     DELETE.
  62.  
  63.     Usage example, perform and HTTP GET on http://www.google.com/:
  64.       import atom.http
  65.       client = atom.http.HttpClient()
  66.       http_response = client.request('GET', 'http://www.google.com/')
  67.  
  68.     Args:
  69.       operation: str The HTTP operation to be performed. This is usually one
  70.           of 'GET', 'POST', 'PUT', or 'DELETE'
  71.       data: filestream, list of parts, or other object which can be converted
  72.           to a string. Should be set to None when performing a GET or DELETE.
  73.           If data is a file-like object which can be read, this method will 
  74.           read a chunk of 100K bytes at a time and send them. 
  75.           If the data is a list of parts to be sent, each part will be 
  76.           evaluated and sent.
  77.       url: The full URL to which the request should be sent. Can be a string
  78.           or atom.url.Url.
  79.       headers: dict of strings. HTTP headers which should be sent
  80.           in the request. 
  81.     """
  82.     if not isinstance(url, atom.url.Url):
  83.       if isinstance(url, types.StringTypes):
  84.         url = atom.url.parse_url(url)
  85.       else:
  86.         raise atom.http_interface.UnparsableUrlObject('Unable to parse url '
  87.             'parameter because it was not a string or atom.url.Url')
  88.     
  89.     all_headers = self.headers.copy()
  90.     if headers:
  91.       all_headers.update(headers) 
  92.  
  93.     connection = self._prepare_connection(url, all_headers)
  94.  
  95.     if self.debug:
  96.       connection.debuglevel = 1
  97.  
  98.     connection.putrequest(operation, self._get_access_url(url), 
  99.         skip_host=True)
  100.     connection.putheader('Host', url.host)
  101.  
  102.     # Overcome a bug in Python 2.4 and 2.5
  103.     # httplib.HTTPConnection.putrequest adding
  104.     # HTTP request header 'Host: www.google.com:443' instead of
  105.     # 'Host: www.google.com', and thus resulting the error message
  106.     # 'Token invalid - AuthSub token has wrong scope' in the HTTP response.
  107.     if (url.protocol == 'https' and int(url.port or 443) == 443 and
  108.         hasattr(connection, '_buffer') and
  109.         isinstance(connection._buffer, list)):
  110.       header_line = 'Host: %s:443' % url.host
  111.       replacement_header_line = 'Host: %s' % url.host
  112.       try:
  113.         connection._buffer[connection._buffer.index(header_line)] = (
  114.             replacement_header_line)
  115.       except ValueError:  # header_line missing from connection._buffer
  116.         pass
  117.  
  118.     # If the list of headers does not include a Content-Length, attempt to
  119.     # calculate it based on the data object.
  120.     if data and 'Content-Length' not in all_headers:
  121.       if isinstance(data, types.StringTypes):
  122.         all_headers['Content-Length'] = len(data)
  123.       else:
  124.         raise atom.http_interface.ContentLengthRequired('Unable to calculate '
  125.             'the length of the data parameter. Specify a value for '
  126.             'Content-Length')
  127.  
  128.     # Set the content type to the default value if none was set.
  129.     if 'Content-Type' not in all_headers:
  130.       all_headers['Content-Type'] = DEFAULT_CONTENT_TYPE
  131.  
  132.     # Send the HTTP headers.
  133.     for header_name in all_headers:
  134.       connection.putheader(header_name, all_headers[header_name])
  135.     connection.endheaders()
  136.  
  137.     # If there is data, send it in the request.
  138.     if data:
  139.       if isinstance(data, list):
  140.         for data_part in data:
  141.           _send_data_part(data_part, connection)
  142.       else:
  143.         _send_data_part(data, connection)
  144.  
  145.     # Return the HTTP Response from the server.
  146.     return connection.getresponse()
  147.     
  148.   def _prepare_connection(self, url, headers):
  149.     if not isinstance(url, atom.url.Url):
  150.       if isinstance(url, types.StringTypes):
  151.         url = atom.url.parse_url(url)
  152.       else:
  153.         raise atom.http_interface.UnparsableUrlObject('Unable to parse url '
  154.             'parameter because it was not a string or atom.url.Url')
  155.     if url.protocol == 'https':
  156.       if not url.port:
  157.         return httplib.HTTPSConnection(url.host)
  158.       return httplib.HTTPSConnection(url.host, int(url.port))
  159.     else:
  160.       if not url.port:
  161.         return httplib.HTTPConnection(url.host)
  162.       return httplib.HTTPConnection(url.host, int(url.port))
  163.  
  164.   def _get_access_url(self, url):
  165.     return url.to_string()
  166.  
  167.  
  168. class ProxiedHttpClient(HttpClient):
  169.   """Performs an HTTP request through a proxy.
  170.   
  171.   The proxy settings are obtained from enviroment variables. The URL of the 
  172.   proxy server is assumed to be stored in the environment variables 
  173.   'https_proxy' and 'http_proxy' respectively. If the proxy server requires
  174.   a Basic Auth authorization header, the username and password are expected to 
  175.   be in the 'proxy-username' or 'proxy_username' variable and the 
  176.   'proxy-password' or 'proxy_password' variable.
  177.   
  178.   After connecting to the proxy server, the request is completed as in 
  179.   HttpClient.request.
  180.   """
  181.   def _prepare_connection(self, url, headers):
  182.     proxy_auth = _get_proxy_auth()
  183.     if url.protocol == 'https':
  184.       # destination is https
  185.       proxy = os.environ.get('https_proxy')
  186.       if proxy:
  187.         # Set any proxy auth headers 
  188.         if proxy_auth:
  189.           proxy_auth = 'Proxy-authorization: %s' % proxy_auth
  190.           
  191.         # Construct the proxy connect command.
  192.         port = url.port
  193.         if not port:
  194.           port = '443'
  195.         proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (url.host, port)
  196.         
  197.         # Set the user agent to send to the proxy
  198.         if headers and 'User-Agent' in headers:
  199.           user_agent = 'User-Agent: %s\r\n' % (headers['User-Agent'])
  200.         else:
  201.           user_agent = ''
  202.         
  203.         proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, user_agent)
  204.         
  205.         # Find the proxy host and port.
  206.         proxy_url = atom.url.parse_url(proxy)
  207.         if not proxy_url.port:
  208.           proxy_url.port = '80'
  209.         
  210.         # Connect to the proxy server, very simple recv and error checking
  211.         p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  212.         p_sock.connect((proxy_url.host, int(proxy_url.port)))
  213.         p_sock.sendall(proxy_pieces)
  214.         response = ''
  215.  
  216.         # Wait for the full response.
  217.         while response.find("\r\n\r\n") == -1:
  218.           response += p_sock.recv(8192)
  219.        
  220.         p_status = response.split()[1]
  221.         if p_status != str(200):
  222.           raise ProxyError('Error status=%s' % str(p_status))
  223.  
  224.         # Trivial setup for ssl socket.
  225.         ssl = socket.ssl(p_sock, None, None)
  226.         fake_sock = httplib.FakeSocket(p_sock, ssl)
  227.  
  228.         # Initalize httplib and replace with the proxy socket.
  229.         connection = httplib.HTTPConnection(proxy_url.host)
  230.         connection.sock=fake_sock
  231.         return connection
  232.       else:
  233.         # The request was HTTPS, but there was no https_proxy set.
  234.         return HttpClient._prepare_connection(self, url, headers)
  235.     else:
  236.       proxy = os.environ.get('http_proxy')
  237.       if proxy:
  238.         # Find the proxy host and port.
  239.         proxy_url = atom.url.parse_url(proxy)
  240.         if not proxy_url.port:
  241.           proxy_url.port = '80'
  242.         
  243.         if proxy_auth:
  244.           headers['Proxy-Authorization'] = proxy_auth.strip()
  245.  
  246.         return httplib.HTTPConnection(proxy_url.host, int(proxy_url.port))
  247.       else:
  248.         # The request was HTTP, but there was no http_proxy set.
  249.         return HttpClient._prepare_connection(self, url, headers)
  250.  
  251.   def _get_access_url(self, url):
  252.     return url.to_string()
  253.  
  254.  
  255. def _get_proxy_auth():
  256.   proxy_username = os.environ.get('proxy-username')
  257.   if not proxy_username:
  258.     proxy_username = os.environ.get('proxy_username')
  259.   proxy_password = os.environ.get('proxy-password')
  260.   if not proxy_password:
  261.     proxy_password = os.environ.get('proxy_password')
  262.   if proxy_username:
  263.     user_auth = base64.encodestring('%s:%s' % (proxy_username,
  264.                                                proxy_password))
  265.     return 'Basic %s\r\n' % (user_auth.strip())
  266.   else:
  267.     return ''
  268.  
  269.  
  270. def _send_data_part(data, connection):
  271.   if isinstance(data, types.StringTypes):
  272.     connection.send(data)
  273.     return
  274.   # Check to see if data is a file-like object that has a read method.
  275.   elif hasattr(data, 'read'):
  276.     # Read the file and send it a chunk at a time.
  277.     while 1:
  278.       binarydata = data.read(100000)
  279.       if binarydata == '': break
  280.       connection.send(binarydata)
  281.     return
  282.   else:
  283.     # The data object was not a file.
  284.     # Try to convert to a string and send the data.
  285.     connection.send(str(data))
  286.     return
  287.